<script lang="ts" setup>
import { ref,unref} from 'vue';

import { useVbenModal, z } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter';
import {show,save, update } from '#/api/system/user';

import { formSchamas } from './schemas';

const record = ref();
const isUpdate = ref(false);
const gridApi = ref();

const [UserForm, formApi] = useVbenForm({
  showDefaultActions: false,
  ...formSchamas,
});
const [Modal, modalApi] = useVbenModal({
  draggable: true,
  onOpenChange(isOpen) {
    if (!isUpdate.value) {
      formApi.updateSchema([
        {
          fieldName: 'confirmPassword',
          rules: z
            .string()
            .regex(
              /[\w!@#$%^&*]{5,18}/,
              '密码由5-18位数字、字母、特殊字符组成。',
            )
            .refine(
              async (confirmPassword) => {
                const values = await formApi.getValues();
                return confirmPassword === values.password;
              },
              {
                message: '确认密码必须与密码一致',
              },
            ),
        },
      ]);
    }
    isUpdate.value = modalApi.getData()?.isUpdate ?? false;
    record.value = isOpen ? modalApi.getData()?.record || {} : {};
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen && isUpdate.value) {
      show(record.value?.id).then((data) => {
        formApi.setValues(data);
      });
    } else {
      formApi.setValues(record.value);
    }
  },
  onConfirm() {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = unref(isUpdate) ? update : save;
        const apiParams = unref(isUpdate) ? [record.value?.id, values] : [values];
       // 调用 API 方法
       //@ts-ignore
        submitApi(...apiParams)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
  },
});
defineExpose(modalApi);
</script>
<template>
  <Modal :title="isUpdate ? '编辑用户' : '新增用户'" class="w-[50%]">
    <div class="common-form">
      <UserForm />
    </div>
  </Modal>
</template>
<style scoped lang="less">
// @import '#/assets/styles/common-form.less';
</style>
